<template>
  <BasicDrawer 
    v-bind="$attrs" 
    @register="registerDrawer" 
    title="登录配置" 
    width="700px" 
    showFooter 
    destroy-on-close
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm"> 
      <template #configKey="{ model, field }">
        <a-row :gutter="8">
          <a-col :sm="20" :md="20" :lg="20" :xl="20">
            <JDictSelectTag 
              placeholder="请选择配置" 
              v-model:value="model[field]"
              dictCode="config_key" 
              showSearch 
            />
          </a-col>
          <a-col :sm="4" :md="4" :lg="4" :xl="4">
            <a-button block style="width: 100%" @click="handleGoConfigParams(model[field])" >去配置</a-button>
          </a-col>
        </a-row>
      </template>

      <template #bindClient="{ model, field }">
        <MyCheckbox v-model:value="checkedClient" :options="clientOptions" />
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup>
  import {ref, computed, unref, onMounted, nextTick} from 'vue';
  import { JDictSelectTag } from '/@/components/Form';
  import {BasicDrawer, useDrawer, useDrawerInner} from '/@/components/Drawer';
  import {BasicForm, useForm} from '/@/components/Form/index';
  import { saveOrUpdateLdpConnect } from './api';
  import { formSchema } from './data';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { PageEnum } from '/@/enums/pageEnum';
  import { MyCheckbox } from '/@/components/Form/index';
  import { listClient } from '/@/views/system/oauthClient/api';

  const clientOptions = ref<any[]>([])
  const { createMessage } = useMessage();
  const extLdpConnect = ref<any>({})
  const ldpId = ref<any>()
  const [registerForm, {setProps, resetFields, setFieldsValue, validate}] = useForm({
    labelWidth: 100,
    baseColProps: { lg: 24, md: 24 },
    wrapperCol: { lg: 24, md: 24 },
    schemas: formSchema,
    showActionButtonGroup: false,
  });
  const emit = defineEmits(['success', 'register']);

  const loading = ref(false);
  const checkedClient = ref<string>()
  const isUpdate = ref(true);
  const [registerDrawer, {setDrawerProps, closeDrawer}] = useDrawerInner(async (data) => {
    await reset()
    extLdpConnect.value = unref(data.record)
    ldpId.value = data.ldpId

    setDrawerProps({confirmLoading: false, loading:true});
    try {
      isUpdate.value = !!data?.isUpdate;
      console.log('data', extLdpConnect.value);
    
      if (unref(isUpdate)) {
        let oauthClientResp
        if (extLdpConnect.value.grantType) {
          oauthClientResp = await listClient({ extGrantType: extLdpConnect.value.grantType })
          clientOptions.value = oauthClientResp.list?.map(e => ({
            label: e.name,
            value: e.id
          }))
          checkedClient.value = oauthClientResp.checkedList?.join(',')
        }
        nextTick(async () => {
          await setFieldsValue({ 
            ...unref(extLdpConnect),
            hasClient: clientOptions.value.length > 0 ? '1' : '0',
            scenes: extLdpConnect.value.scenes?.split(',')
          })
        })
      }
    } finally {
      setDrawerProps({loading:false});
    }
    
  });

  const handleGoConfigParams = (configKey) => {
    console.log('configKey', configKey);
    
    if (!configKey || configKey === '' || configKey?.length === 0) {
      createMessage.warning('请先选择配置')
      return
    }
    const url = `${PageEnum.CONFIG_CENTER}?configKey=${configKey}`
    window.open(url, '_blank')
  }

  const reset = async () => {
    await resetFields()
    clientOptions.value = []
    extLdpConnect.value = {}
    checkedClient.value = ''
  }
  async function handleSubmit(exit) {
    setDrawerProps({ confirmLoading: true })
    try {
      let values = await validate();
      delete values['bindClient']
      const from = { 
        ...values, 
        ldpId: unref(ldpId),
        authClientIds: unref(checkedClient)?.split(','),
      }
      console.log("from", from);
      
      loading.value = true;
      await saveOrUpdateLdpConnect(from, unref(isUpdate));
      closeDrawer()
      emit('success');
      createMessage.success("操作成功")
    } finally {
      setDrawerProps({ confirmLoading: false })
      loading.value = false;
    }
  }
</script>
